//
//  RequestManager.m
//  product_B
//
//  Created by zyc on 16/5/27.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager
+ (NSData *)dicToDataWithDic:(NSDictionary *)dic{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic) {
        NSString *string = [NSString stringWithFormat:@"%@=%@", key, dic[key]];
        [array addObject:string];
    }
    NSString *dataString = [array componentsJoinedByString:@"&"];
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}

+ (void)initWithUrlString:(NSString *)urlString requestType:(NSString *)requestType parDic:(NSDictionary *)parDic finishBlock:(RequestFinish)finishBlock errorBlock:(RequestError)errorBlock{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    if ([requestType isEqualToString:@"POST"]) {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0) {
            [request setHTTPBody:[self dicToDataWithDic:parDic]];
        }
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                //error存在就代表请求失败
                if (errorBlock) {
                    errorBlock(error);
                }
            } else {
                //不存在error就代表成功
                if (finishBlock) {
                    finishBlock(data);
                }
            }
        });
        
    }];
    [task resume];
}

@end
